package com.bigflexlib.x.flash.utils.Timer
{
	import flash.utils.Timer;
	import flash.display.Stage;
	import flash.events.TimerEvent;
	import flash.events.Event;

	import mx.managers.SystemManagerGlobals;
	
	/**
	 * 
	 * delay is measured in frames instead of milliseconds
	 * if you set delay=3 and repeatCount=2 you would get the following events
	 * enterframe
	 * enterframe
	 * enterframe
	 * timer
	 * enterframe
	 * enterframe
	 * enterframe
	 * timer
	 * timercomplete
	 * enterframe
	 * enterframe
	 * ...
	 * 
	 * @author aldo.bucchi@gmail.com
	 * 
	 */	
	public class FrameTimer extends Timer
	{
		
		
		////////////////////////////////////
		// frameCount
		////////////////////////////////////
		
		
		private var frameCount:int = 0;
		
		
		

		////////////////////////////////////
		// currentCount
		////////////////////////////////////		
		
		private var _currentCount:int = 0;
		
		override public function get currentCount( ):int
		{
			return _currentCount;
		}
		
		
		
		////////////////////////////////////
		// 
		////////////////////////////////////			

		private function get stage( ):Stage
		{
			return SystemManagerGlobals.topLevelSystemManagers[0].stage as Stage;	
		}
		
		
		
		
	
		public function FrameTimer( delay:int, repeatCount:int=0 )
		{
			super( delay, repeatCount );
		}
	
	
	
	
		override public function start():void
		{
			stage.addEventListener( Event.ENTER_FRAME, onEnterFrame );
		}
		
	
	
	
	
		
		private function onEnterFrame( event:Event ):void
		{
			
			if ( ( ++frameCount % delay ) == 0 )
			{
				
				
				_currentCount++;
				
				var complete:Boolean = ( repeatCount != 0 ) && ( _currentCount == repeatCount );
								
				if ( complete )
					stage.removeEventListener( Event.ENTER_FRAME, onEnterFrame );

				dispatchEvent( new TimerEvent( TimerEvent.TIMER ) );
				
				if ( complete )
					dispatchEvent( new TimerEvent( TimerEvent.TIMER_COMPLETE ) );
			}
			
		}
		
		
		
		
		override public function stop( ):void
		{
			stage.removeEventListener( Event.ENTER_FRAME, onEnterFrame );		
		}
		
		
		
		
		override public function reset( ):void
		{
			
			_currentCount = 0;
			frameCount = 0;	
			stage.removeEventListener( Event.ENTER_FRAME, onEnterFrame );
		}
	
	
	}
	
}